package com.example.baweyplayer.singletons;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;

import android.util.Log;

import com.example.baweyplayer.internals.Song;

public class PlaybackQueue {

	private static PlaybackQueue instance = null;

	protected PlaybackQueue() {
	}

	public static PlaybackQueue getInstance() {
		if (instance == null) {
			synchronized (PlaybackQueue.class) {
				if (instance == null) {
					instance = new PlaybackQueue();
				}
			}
		}
		return instance;
	}

	private LinkedList<Song> playbackQueue = new LinkedList<Song>();
	private int currentTrack = 0;

	public void enqueue(Song song) {
		playbackQueue.add(song);
	}

	public void enqueueAll(Collection<Song> songs) {
		playbackQueue.addAll(songs);
		Log.d("baweyTest", "Added " + songs.size() + " songs to queue");
	}

	public void shuffle() {
		Collections.shuffle(playbackQueue);
	}

	public int nextTrack() {
		if (playbackQueue.size() > 0) {
			currentTrack = (currentTrack + 1) % playbackQueue.size();
		}
		return currentTrack;
	}

	public int previousTrack() {
		if (playbackQueue.size() > 0) {
			currentTrack = (playbackQueue.size() + currentTrack - 1)
					% playbackQueue.size();

		}
		Log.d("d", "prevTrack result=" + currentTrack);
		return currentTrack;
	}

	public Song getCurrentTrack() {
		if (playbackQueue.size() > 0) {
			return playbackQueue.get(currentTrack);
		} else {
			return null;
		}
	}

	// something...
	public Song getNextTrack(boolean restartEnabled) {
		if (nextTrack() != 0 || restartEnabled) {
			return getCurrentTrack();
		} else {
			return null;
		}
	}

	// jailed at first track if no restart allowed
	public Song getPreviousTrack(boolean restartEnabled) {
		if (currentTrack != 0 || restartEnabled) {
			previousTrack();
		}
		return getCurrentTrack();
	}

	/**
	 * CRUDE method to return some info about the track
	 * 
	 * @return
	 */
	public String getCurrentTrackInfo() {
		Song track = getCurrentTrack();
		if (track != null) {
			return track.getName();
		} else {
			return "";
		}
	}
}
